//
//  MesageTableViewController.m
//  YaoHeAPP
//
//  Created by xyh on 15/12/17.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "MesageTableViewController.h"
#import "Controller.h"
#import "SVPullToRefresh.h"
#import "Masonry.h"
@interface MesageTableViewController () {
    NSMutableArray *arrayList;//报价数组；
}

@property (nonatomic, assign)NSInteger  page;//页数

@end

@implementation MesageTableViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.tableView triggerPullToRefresh];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"MesageTableViewController"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"MesageTableViewController"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationController.navigationBar.hidden=YES;
//    self.title=@"消息通知";
//    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bg_user_center"]forBarMetrics:UIBarMetricsDefault];
//   
//    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
//    
//    //改变字体颜色
//     [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    
    
    
    self.view.backgroundColor=bgVCcolor;
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(kNavigationBarHeight);  make.right.offset(0);
    }];
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"快速注册";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(self.view.frame.size.width/2-50);
        make.width.offset(100);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton*leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(24);
        make.height.offset(22);
        make.bottom.offset(-12);
    }];
    
    
    
    
    
    self.tableView.frame=CGRectMake(0, kNavigationBarHeight, self.view.frame.size.width, self.view.frame.size.height-kNavigationBarHeight);
    
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;//确保TablView能够正确的调整大小
    //定义数组
    arrayList=[[NSMutableArray alloc]init];
    
    
    __weak MesageTableViewController *weakSelf = self;
    
    // setup pull-to-refresh
    [self.tableView addPullToRefreshWithActionHandler:^{
        [weakSelf insertRowAtTop];
    }];
    
    // setup infinite scrolling
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf insertRowAtBottom];
    }];
    

}

-(void)backLogin
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)insertRowAtTop {
    __weak MesageTableViewController *weakSelf = self;
    
    [weakSelf.tableView beginUpdates];
    _page=1;
    NSNumber*number1=[NSNumber numberWithInteger:1];
    NSNumber*number2=[NSNumber numberWithInteger:10];
    NSDictionary*di=@{@"page_num":number1,@"page_step":number2};
    
    [Controller requestWithURL:MESAGENOTI jsondic:di finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            [arrayList removeAllObjects];
            [arrayList addObjectsFromArray:data.data[@"MESSAGE_INFOS"]];
            [self.tableView reloadData];
        }
        else
        {
            
        }
    }];
    
    // 3. 结束刷新(相当于动画)
    [weakSelf.tableView endUpdates];
    [weakSelf.tableView.pullToRefreshView stopAnimating];

}


- (void)insertRowAtBottom {
    
    __weak MesageTableViewController *weakSelf = self;
    
    [weakSelf.tableView beginUpdates];
    
    _page=_page+1;
    NSNumber*number1=[NSNumber numberWithInteger:_page];
    NSNumber*number2=[NSNumber numberWithInteger:10];
    NSDictionary*di=@{@"page_num":number1,@"page_step":number2};
   [Controller requestWithURL:MESAGENOTI jsondic:di finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            [arrayList addObjectsFromArray:data.data[@"MESSAGE_INFOS"]];
            
            [self.tableView reloadData];
            
        }
        else
        {
            
        }
    }];
    
    [weakSelf.tableView endUpdates];
    [weakSelf.tableView.infiniteScrollingView stopAnimating];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//
//    return 1;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return arrayList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 90;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //指定cellIdentifier为自定义的cell
    static NSString *CellIdentifier = @"MesageListCell";
    
    //自定义cell类有图片
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    UILabel *nam=nil;
    UILabel *ti=nil;

        if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    
        UILabel *namela=[[UILabel alloc]initWithFrame:CGRectMake(15, 20, self.view.frame.size.width-30, 30)];
        namela.tag=20;
            namela.font=[UIFont systemFontOfSize:11];
        [cell addSubview:namela];
        
         UILabel *timela=[[UILabel alloc]initWithFrame:CGRectMake(15, 55, self.view.frame.size.width-30, 20)];
            timela.font=[UIFont systemFontOfSize:10];
        timela.tag=21;
         [cell addSubview:timela];
        
    }
    
    
    nam=[cell viewWithTag:20];
    ti=[cell viewWithTag:21];
    
       nam.text=arrayList[indexPath.row][@"CONTENT"];
    
//    nam.text=[NSString stringWithFormat:@"%ld",(long)indexPath.row];
    //字符串截取
    NSString *tt=arrayList[indexPath.row][@"CREATE_TIME"];
    
    NSString *a =[tt substringWithRange:NSMakeRange(6, 10)];
    //后台截取时间
    NSInteger tiu=[a integerValue];
    
    //当前时间
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a1=[dat timeIntervalSince1970];
    NSInteger oo=(long)a1;
    
    //换算时间差
    NSInteger timcha=oo-tiu;
    
    if (timcha<0) {
        //刚刚
        ti.text=@"刚刚";
        
    }else if(timcha<60){
        //多少秒前
        NSString *n=[NSString stringWithFormat:@"%ld秒前",(long)timcha];
        ti.text=n;
    }else if(timcha>=60&&timcha/60<60){
        //多少分钟前
        NSString *n=[NSString stringWithFormat:@"%d分钟前",timcha/6];
        ti.text=n;
        
        
    }else if(timcha/60>=60&&timcha/60/60<24){
        //多少小时前
        NSString *n=[NSString stringWithFormat:@"%d小时前",timcha/3600];
        ti.text=n;
        
    }else if(timcha/60/60>=24){
        //显示日期
        
        NSDate *con = [NSDate dateWithTimeIntervalSince1970:tiu];
        
        //实例化一个NSDateFormatter对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设定时间格式,这里可以设置成自己需要的格式
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        //用[NSDate date]可以获取系统当前时间
        NSString *currentDateStr = [dateFormatter stringFromDate:con];
        
        ti.text=currentDateStr;

        
    }
    
    
    return cell;
}




//要求委托方的编辑风格在表视图的一个特定的位置。
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCellEditingStyle result = UITableViewCellEditingStyleNone;//默认没有编辑风格
    if ([tableView isEqual:self.tableView]) {
        result = UITableViewCellEditingStyleDelete;//设置编辑风格为删除风格
    }
    return result;
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated{//设置是否显示一个可编辑视图的视图控制器。
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];//切换接收者的进入和退出编辑模式。
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{//请求数据源提交的插入或删除指定行接收者。
    if (editingStyle ==UITableViewCellEditingStyleDelete) {//如果编辑样式为删除样式
        if (indexPath.row<[arrayList count]) {
            [arrayList removeObjectAtIndex:indexPath.row];//移除数据源的数据
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];//移除tableView中的数据
        }
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
